const addressDB = require("../db/addressDB");

exports.getAddress = async function (ctx) {
  const id = ctx.state.user.id;
  const result = await addressDB.getAddress({ uid: id });
  try {
    ctx.body = {
      code: 200,
      message: "请求成功",
      data: result,
    };
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "请求失败",
      error,
    };
  }
};
exports.getAddressByID = async function (ctx) {
  ctx.verifyParams({
    id: "string",
  });
  const id = ctx.params.id;
  try {
    const result = await addressDB.getAddressByID({ id: id });
    if (result.length) {
      ctx.body = {
        code: 200,
        message: "请求成功",
        data: result[0],
      };
    } else {
      ctx.body = {
        code: 404,
        message: "数据未找到",
      };
    }
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "请求失败",
      error,
    };
  }
};
exports.delAddress = async function (ctx) {
  ctx.verifyParams({
    id: "string",
  });
  const id = ctx.params.id;
  const uid = ctx.state.user.id;
  try {
    const result = await addressDB.delAddressByID({ id, uid });
    if (result.affectedRows) {
      ctx.body = {
        code: 200,
        message: "数据删除成功",
      };
    } else {
      ctx.body = {
        code: 400,
        message: "数据删除失败",
      };
    }
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "数据库操作异常",
      error: error,
    };
  }
};
exports.editAddress = async function (ctx) {
  ctx.verifyParams({
    id: "string",
    tel: "string",
    nickname: "string",
    provice_city_area: "string",
    longitude: "string",
    latitude: "string",
  });
  const result = await addressDB.editAddressByID(ctx.request.body);
  try {
    ctx.body = {
      code: 200,
      message: '数据修改成功',
      data: result
    }
  } catch (error) {
    ctx.body = {
      code: 400,
      message: "数据库操作错误",
      error: error,
    };
  }

};

exports.addAddress = async function (ctx) {
  // tel,
  // nickname,
  // provice_city_area,
  // detail_address,
  // longitude,
  // latitude,
  ctx.verifyParams({
    tel: "string",
    nickname: "string",
    provice_city_area: "string",
    detail_address: "string",
    longitude: "string",
    latitude: "string",
  });
  const user = ctx.state.user;
  const data = ctx.request.body;
  const result = await addressDB.addAddress({ ...data, uid: user.id });
  ctx.body = result;
  if (result.affectedRows) {
    ctx.body = {
      code: 200,
      message: "地址添加成功",
    };
  } else {
    ctx.body = {
      code: 400,
      message: "操作失败",
      error: result,
    };
  }
};
